package com.chat.app.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chat.app.entity.TAppUser;
import com.chat.app.mapper.TAppUserMapper;
import com.chat.common.exception.CustomException;
import com.chat.common.model.Constant;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 获取当前登录用户工具类
 *
 * @author xiaoqiang
 * @date 2020/8/3 11:45
 */
@Component
public class UserUtil {


    @Autowired
    private TAppUserMapper tAppUserMapper;


    /**
     * 获取当前登录用户
     *
     * @param
     * @return com.wang.model.UserDto
     * @author xiaoqiang
     * @date 2020/8/3 11:45
     */
    public TAppUser getTAppUser() {
        String token = SecurityUtils.getSubject().getPrincipal().toString();
        // 解密获得Account
        String username = JwtUtil.getClaim(token, Constant.USERNAME);
        TAppUser user = tAppUserMapper.selectOne(new LambdaQueryWrapper<TAppUser>().eq(TAppUser::getUsername, username));
        // 用户是否存在
        if (user == null) {
            throw new CustomException("该帐号不存在(The account does not exist.)");
        }
        return user;
    }

    /**
     * 获取当前登录用户Id
     *
     * @param
     * @return com.wang.model.UserDto
     * @author xiaoqiang
     * @date 2020/8/3 11:45
     */
    public Long getUserId() {
        return getTAppUser().getUserId();
    }

    /**
     * 获取当前登录用户Token
     *
     * @param
     * @return com.wang.model.UserDto
     * @author xiaoqiang
     * @date 2020/8/3 11:45
     */
    public String getToken() {
        return SecurityUtils.getSubject().getPrincipal().toString();
    }

    /**
     * 获取当前登录用户Account
     *
     * @param
     * @return com.wang.model.UserDto
     * @author xiaoqiang
     * @date 2020/8/3 11:45
     */
    public String getAccount() {
        String token = SecurityUtils.getSubject().getPrincipal().toString();
        // 解密获得Account
        return JwtUtil.getClaim(token, Constant.USERNAME);
    }
}
